package main

import (
    "database/sql"
    "errors"
    "flag"
    "fmt"
    "go.uber.org/zap"
    "google.golang.org/protobuf/proto"
    "laxkits/lib/laxmysql"
    "laxkits/lib/laxoffice"
    "laxkits/lib/laxutils"
    KKSG "laxkits/lib/ropb"
    "laxkits/lib/zlogger"
    "strconv"
)

type XMLNode struct {
    Log zlogger.LaxLogNode `xml:"log"`
    MysqlList []laxmysql.LaxMySQLConfig `xml:"mysqlgroup>mysql"`
}

var xmlconfig  XMLNode

func TryModifyName(csvIndex int, csvRow []string) error {
    if len(csvRow) < 11 {
        zap.S().Errorf("处理行出错:%d, %s", csvIndex, csvRow)
        return errors.New("ModifyError")
    }
    roleId, err := strconv.ParseUint(csvRow[0], 10, 64)
    if err != nil {
        zap.S().Errorf("解析roleid出错,行:%d,%s", csvIndex, csvRow)
        return err
    }
    openId := csvRow[1]
    sid := csvRow[2]
    oldName := csvRow[3]
    newName := csvRow[10]
    conn := laxmysql.GetLaxMySQLMgr().GetById(sid)
    if conn == nil {
        zap.S().Errorf("服务器:%s,没有相应的mysqlconn, 行:%d,%s", sid, csvIndex, csvRow)
        return errors.New("SidError")
    }
    // 更新role表的brief
    if err = conn.QueryRow(fmt.Sprintf("select RoleBrief from player%d.role where id=%d", roleId%5, roleId),
        func(row *sql.Row) error {
            var brief KKSG.RoleBriefInfo
            var b []byte
            if err = row.Scan(&b); err != nil {
                return err
            }
            if err = proto.Unmarshal(b, &brief); err != nil {
                return err
            }
            brief.Name = newName
            b, err = proto.Marshal(&brief)
            if err != nil {
                return err
            }
            affect, err := conn.Execute(fmt.Sprintf("update player%d.role set RoleBrief=? where id = ?",
                roleId%5),
                b,
                roleId)
            if err != nil {
                return err
            }
            zap.S().Infof("修改角色idx[%d]角色[%d]的brief成功,行数:%d", csvIndex, roleId, affect)
            return nil
        }); err != nil {
        if err == sql.ErrNoRows {
            zap.S().Infof("角色没有，不修改,rowIndex[%d],[%s]", csvIndex, csvRow)
            return nil
        }
        return err
    }
    // 更新role表的name
    rowAffect, err := conn.Execute(fmt.Sprintf("update player%d.role set name='%s' where id=%d",
        roleId%5,
        newName,
        roleId))
    if err != nil {
        zap.S().Errorf("更新失败:%v", err)
        return err
    }
    zap.S().Infof("openid[%s]旧名[%s]更新成新名[%s]成功,角色id[%d],服务器[%s],影响行:%d,csv行[%d]",
        openId,
        oldName,
        newName,
        roleId,
        sid,
        rowAffect,
        csvIndex)
    return nil
}

func TypeModify() {
    if err := laxoffice.CSVEachRow("./modify.csv", 1, TryModifyName); err != nil {
        zap.S().Warnf("读取csv出错:%v", err)
        return
    }
}

func main() {
    var execType string
    flag.StringVar(&execType, "t", "Unknown", "<modify> <query> <sync>")
    flag.Parse()
    fmt.Println("type:", execType)
    if err := laxutils.LoadXmlFile("conf.xml", &xmlconfig); err != nil {
        fmt.Println("加载xml配置失败")
        return
    }
    zlogger.InitLogger(&xmlconfig.Log)
    if err := laxmysql.GetLaxMySQLMgr().RegisterByConfig(xmlconfig.MysqlList); err != nil {
        zap.S().Errorf("注册数据库失败:%v", err)
        return
    }
    defer laxmysql.GetLaxMySQLMgr().CloseAll()
    go func() {
        if execType == "modify" {
            TypeModify()
        } else if execType == "query" {
            TypeQuery()
        } else if execType == "sync" {
            TypeSync()
        } else {
            zap.S().Errorf("参数[%s]非法,合法的有<query> <sync> <modify>", execType)
        }
    }()
    laxutils.CloseGracefully(nil)
}
